//
//  LZPlaceholderTextView.swift
//  Weibo
//
//  Created by lzing on 16/3/31.
//  Copyright © 2016年 lzing. All rights reserved.
//

import UIKit

class LZPlaceholderTextView: UITextView {
    //MARK: - attribute
    override var text: String? {
        didSet {
            // 有文本就隐藏
            placeholdTextLabel.hidden = self.hasText()
        }
    }
    
    override var font: UIFont? {
        didSet {
            placeholdTextLabel.font = font
        }
    }
    
    var placeholdText: String? {
        didSet {
            placeholdTextLabel.text = placeholdText
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        // 添加子控件
        addSubview(placeholdTextLabel)
        // 添加约束
        placeholdTextLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeholdTextLabel, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeholdTextLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
        // 监听通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textViewDidChange", name: UITextViewTextDidChangeNotification, object: self)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //MARK: - notification callBack
    @objc private func textViewDidChange() {
        // 当有文本的时候,隐藏label
        placeholdTextLabel.hidden = self.hasText()
    }
    
    //MARK: - lazy
    private lazy var placeholdTextLabel : UILabel = {
        // 添加label
        let placeholderLabel = UILabel()
        placeholderLabel.textColor = UIColor.lightGrayColor()
        placeholderLabel.sizeToFit()
        
        return placeholderLabel
    }()
}

//MARK: - <UITextViewDelegate>
extension LZPlaceholderTextView : UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        // 当有文本的时候,隐藏label
        placeholdTextLabel.hidden = textView.hasText()
    }
}
